package framework.utils;

import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * Spring容器相关工具类
 * @ClassName: SpringUtils
 * @Description: 
 * @author baolin.liu  
 * @date 2015-9-6 上午10:18:53
 * @version V1.0
 */
public final class SpringUtils
{
	public static final <T> T getBean(String name, Class<T> clazz)
	{
		try
		{
			WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
			return (T)context.getBean(name, clazz);
		}
		catch (Exception e)
		{
			return null;
		}
	}

	public static final Object getBean(String name)
	{
		try
		{
			WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
			return context.getBean(name);
		}
		catch (Exception e)
		{
			return null;
		}
	}

	public static final <T> T getBean(Class<T> t)
	{
		try
		{
			WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
			return (T)context.getBean(t.getName());
		}
		catch (Exception e)
		{
			return null;
		}
	}

	public static final ServletContext getServletContext()
	{
		try
		{
			return ContextLoader.getCurrentWebApplicationContext().getServletContext();
		}
		catch (Exception e)
		{
			return null;
		}
	}

	public static final HttpServletRequest getRequest()
	{
		RequestAttributes attributes = RequestContextHolder.currentRequestAttributes();
		if (attributes == null)
			return null;

		if (attributes instanceof ServletRequestAttributes)
			return ((ServletRequestAttributes)attributes).getRequest();

		return null;
	}
	
	/**
	 * 根据key值获取spring托管中的properties配置值
	 * @Title: getProperty
	 * @author baolin.liu 
	 * @date 2015-11-9 下午05:56:26
	 * @param key
	 * @return String
	 */
	public static String getProperty(String key){
		if(SpringUtils.getBean("propertiesReader") == null){
			return null;
		}
		return (String)((Properties)SpringUtils.getBean("propertiesReader")).get(key);
	}
}